<?php
class AuthController extends Zend_Controller_Action
{
	function indexAction()
	{
		echo 'You are calling a user function';
	}

	function loginAction()
	{
		if($this->_request->isPost())
		{
			$errors = array();
			try{				
				Zend_Loader::loadClass('Zend_Validate');
				//get Request Params use method getParam()
				if(!Zend_Validate::is($this->getRequest()->getParam('username'), 'NotEmpty')) {
					$errors[] = 'Please input your login name!';
				} else {
					$this->view->username = $this->_getParam('username');
				}
				Zend_Loader::loadClass('Zend_Filter_StripTags');
				$filter = new Zend_Filter_StripTags();
				$name = $filter->filter($_POST['username']);
				
				if(count($errors) <1 && !Zend_Validate::is($_POST['password'],'NotEmpty'))
				{
					$errors[] = 'Please input your pasword!';
				}
				$password = $filter->filter($_POST['password']);
				
				if(count($errors) <1)
				{					
					$dbAdapter = Zend_Registry :: get('db_adapter');
					Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');					
					$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                    //we can use chain
					$authAdapter->setTableName('tt_user')
					            ->setIdentityColumn('name')
					            ->setCredentialColumn('passwd')					
					            ->setIdentity($name)
					            ->setCredential($password);

					$auth = Zend_Auth::getInstance();
					$rs = $auth->authenticate($authAdapter);
					if($rs->isValid())
					{	
						$this->_helper->viewRenderer->setNoRender();						
						$this->_redirect('/task/');
					}
					else
					{
						$errors[] = "Login information incorrect. Please try again.";
					}
				}
				$this->view->errors = $errors;
			}
			catch (Exception $e)
			{
				echo "Caught exception: " . get_class($e) . "\n";
				echo "Message: " . $e->getMessage() . "\n";
			}
		}
	}

	function logoutAction()
	{		
		Zend_Auth::getInstance()->clearIdentity();
	}
}